package me.khrystal.store.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.khrystal.store.R;
import me.khrystal.store.base.BaseActivity;
import me.khrystal.store.bean.App;
import me.khrystal.store.bean.CommonResp;
import me.khrystal.store.callback.JsonCallback;
import me.khrystal.store.callback.LogDownloadListener;
import me.khrystal.store.http.DownloadQueueStatus;
import me.khrystal.store.http.HttpRequest;
import me.khrystal.store.utils.StringUtil;
import me.khrystal.store.widget.RatingBar;

/**
 * usage: 应用详情页
 * author: kHRYSTAL
 * create time: 17/7/15
 * update time:
 * email: 723526676@qq.com
 */

public class AppDetailActivity extends BaseActivity {
    private static final String TAG = AppDetailActivity.class.getSimpleName();
    public static final String INK_APP_NAME = "ink_app_name";
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.ivIcon)
    ImageView ivIcon;
    @Bind(R.id.tvName)
    TextView tvName;
    @Bind(R.id.tvRating)
    TextView tvRating;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.btnDownloadSmall)
    Button btnDownloadSmall;
    @Bind(R.id.rlDeatilHeader)
    RelativeLayout rlDeatilHeader;
    @Bind(R.id.tvDetailBody)
    TextView tvDetailBody;
    @Bind(R.id.tvDownloadBig)
    TextView tvDownloadBig;
    @Bind(R.id.rlContent)
    RelativeLayout rlContent;
    @Bind(R.id.tvTips)
    TextView tvTips;
    @Bind(R.id.btnReload)
    Button btnReload;
    @Bind(R.id.errorView)
    RelativeLayout errorView;

    private String mAppName;
    private App mApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        ButterKnife.bind(this);
        mAppName = getIntent().getStringExtra(INK_APP_NAME);
        if (StringUtil.isNullOrEmpty(mAppName))
            finish();

        initView();
        fetchAppDetail();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("应用详情");
        toolbar.setTitleTextColor(Color.WHITE);
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.download:
                        startActivity(new Intent(AppDetailActivity.this, DownloadManagerActivity.class));
                        break;
                }
                return true;
            }
        });
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        ratingBar.setClickable(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void fetchAppDetail() {
        showProgress("正在加载, 请稍后..");
        HttpRequest.getInstance().getAppDetail(this, mAppName)
                .execute(new JsonCallback<CommonResp>(CommonResp.class) {
                    @Override
                    public void onSuccess(Response<CommonResp> response) {
                        dismissProgress();
                        if (response.body().code == 0) {
                            if (response.body().datas != null && !response.body().datas.isEmpty())
                                updateView(response.body().datas.get(0));
                            else {
                                rlContent.setVisibility(View.GONE);
                                errorView.setVisibility(View.VISIBLE);
                                tvTips.setText("获取应用数据为空");
                            }
                        } else {
                            rlContent.setVisibility(View.GONE);
                            errorView.setVisibility(View.VISIBLE);
                            tvTips.setText(response.body().message);
                        }
                    }

                    @Override
                    public void onError(Response<CommonResp> response) {
                        super.onError(response);
                        dismissProgress();
                        rlContent.setVisibility(View.GONE);
                        errorView.setVisibility(View.VISIBLE);
                        tvTips.setText("获取数据失败");
                    }
                });
    }

    /**
     * 拉取接口成功后更新视图
     *
     * @param app
     */
    private void updateView(App app) {
        mApp = app;
        if (!StringUtil.isNullOrEmpty(app.icon))
            Glide.with(this).load(app.icon).into(ivIcon);
        if (!StringUtil.isNullOrEmpty(app.name))
            tvName.setText(String.format("应用名称: %s", app.name));
        if (!StringUtil.isNullOrEmpty(app.description))
            tvDetailBody.setText(app.description);
        // 更新按钮点击状态
        if (OkDownload.getInstance().getTask(HttpRequest.getDownloadUrl(app.name)) != null)
            updateBtnStatus(DownloadQueueStatus.INQUEUE);
        else
            updateBtnStatus(DownloadQueueStatus.NOTINQUEUE);
    }

    @OnClick({R.id.btnDownloadSmall, R.id.tvDownloadBig})
    public void onDownloadClick() {
        if (mApp != null) {
            GetRequest<File> request = OkGo.<File>get(HttpRequest.getDownloadUrl(mApp.name));
            // 参数为tag标识和 请求
            OkDownload.request(HttpRequest.getDownloadUrl(mApp.name), request)
                    .extra1(mApp)
                    .fileName(mApp.name + HttpRequest.APK_SUFFIX) // 文件名
                    .save() // 下载状态 进度写入数据库
                    .register(new LogDownloadListener())
                    .start(); // 注册监听
            // 更新按钮状态
            updateBtnStatus(DownloadQueueStatus.INQUEUE);
        }
    }

    private void updateBtnStatus(DownloadQueueStatus status) {
        if (status == DownloadQueueStatus.INQUEUE) {
            btnDownloadSmall.setEnabled(false);
            tvDownloadBig.setEnabled(false);
            btnDownloadSmall.setText("已在队列");
            tvDownloadBig.setText("已在队列");
        } else {
            btnDownloadSmall.setEnabled(true);
            tvDownloadBig.setEnabled(true);
            btnDownloadSmall.setText("点击下载");
            tvDownloadBig.setText("点击下载");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.download_menu, menu);
        return true;
    }
}
